<template>
  <el-card>
    <template #header>商品编辑</template>
    <!-- <div>{{ getGoodsInfo}}</div> -->
    <el-form
      :model="goodsForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="goodsForm.name"></el-input>
      </el-form-item>
      <el-form-item label="商品分类" prop="category_name">
        <el-select v-model="goodsForm.category_name" placeholder="请选择活动区域">
          <el-option v-for="item in cateArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input v-model.number="goodsForm.price" type="number"></el-input>
      </el-form-item>
      <!-- <el-form-item label="商品总数量" prop="sales_volume">
        <el-input v-model.number="goodsForm.sales_volume" type="number"></el-input>
      </el-form-item>-->
      <el-form-item label="商品图片">
        <el-upload
          class="avatar-uploader"
          action="https://wxopen.besthuishenghuo.com/api/file/pictureUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <img v-else-if="!imageUrl" :src="goodsForm.img_url" alt />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="商品描述" prop="describe">
        <el-input type="textarea" v-model="goodsForm.describe"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">确定修改</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { goodsDetail, goodsEdit, goodsCate } from '@/api/goods'
export default {
  created() {
    // 如果是通过其他查询参数  ?id=2 传入的，那么可以通过this.$route.query访问
    // 如果其他风格  /goods/edit/2   、goods/edit/:id那么通过 this.$route.params
    // console.log(this.$route.params.id)
    this.getGoodsInfo()
    this.goodsCate()
  },
  data() {
    return {
      // 数据对象
      goodsForm: {
        name: '',
        category_name: '',
        price: '',
        sales_volume: '',
        describe: '',
        img_id: ''
      },
      // 规则对象
      rules: {
        name: [
          // required 必须的
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        price: [
          // required 必须的
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        sales_volume: [
          // required 必须的
          { required: true, message: '请输入数量', trigger: 'blur' }
        ],
        category_name: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],

        describe: [
          { required: true, message: '请填写商品描述', trigger: 'blur' }
        ]
      },
      imageUrl: '',
      avatarUrl: '',
      cateArr: []
    }
  },
  methods: {
    async getGoodsInfo() {
      const users = JSON.parse(localStorage.getItem('users') || '{}')
      const { data } = await goodsDetail({
        member_id: users.member_id,
        access_token: users.access_token,
        id: this.$route.params.id
      })
      // console.log(data)
      this.goodsForm = data
    },
    async goodsCate() {
      const users = JSON.parse(localStorage.getItem('users') || '{}')
      const { data } = await goodsCate({
        member_id: users.member_id,
        access_token: users.access_token
      })
      // console.log(data)
      this.cateArr = data
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 因为分类如果是默认的值，那么获取到的就是中文
          const cateItem = this.cateArr.find(
            item => item.name === this.goodsForm.category_name
          )
          let cateId = null
          if (cateItem) {
            cateId = cateItem.id
          } else {
            cateId = this.goodsForm.category_name
          }
          const users = JSON.parse(localStorage.getItem('users') || '{}')
          const { code, msg } = await goodsEdit({
            // 需要携带的参数
            member_id: users.member_id,
            access_token: users.access_token,
            name: this.goodsForm.name,
            category_id: this.goodsForm.category_name,
            price: this.goodsForm.price,
            img_id: this.goodsForm.img_id,
            describe: this.goodsForm.describe,
            id: this.goodsForm.id
          })
          if (code === 1) {
            this.$message.success(msg)
            setTimeout(() => {
              this.$router.push('/goods/list')
            }, 1500)
          } else {
            this.$message.error(msg)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess(res, file) {
      // 处理前端本地属性预览的功能，并不是实质性的上传
      this.imageUrl = URL.createObjectURL(file.raw)

      // 把响应回来的的内容，主要是url地址存储起来，方便下一次请求
      this.goodsForm.img_id = res.data.id
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 400px;

  .el-select {
    width: 300px;
  }
}

.avatar-uploader {
  width: 68px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  // margin-left: 40px;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 68px;
  height: 68px;
  line-height: 68px;
  text-align: center;
}
.avatar {
  width: 68px;
  height: 68px;
  display: block;
}

img {
  width: 60px;
}
</style>
